/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

/**
 * @author Eduardo Cerritos
 */
public class ActualizarEncuestas extends MIDlet implements CommandListener{
    private Thread receptor=null;
    private TextBox txtMensaje=new TextBox("Encuestas Activas", "Encuestas Activas",256, TextField.ANY);
    private Alert alerta;
    private Command cmdSalir = new Command("Salir",Command.EXIT, 0);
    
    public void startApp() {
        Display.getDisplay(this).setCurrent(txtMensaje);
        txtMensaje.addCommand(cmdSalir);
        txtMensaje.setCommandListener(this);
        iniciarRecepcion();
    }

    public void iniciarRecepcion(){
        HttpConnection httpConn = null;
        String url = this.getAppProperty("UrlServidor") + this.getAppProperty("ServletEncuestasActivas");
        OutputStream os = null;
        InputStream is = null;

        try {
            processRequest(url);
          // Abrir una conexion HTTP
//          httpConn = (HttpConnection)Connector.open(url);
//          if(httpConn.getResponseCode()== 200){
//              // Leer la respuesta del servidor
//              StringBuffer sb = new StringBuffer();
//              is = httpConn.openDataInputStream();
//              int chr;
//
//              while ((chr = is.read()) != -1)
//              {
//                sb.append((char) chr);
//              }
//
//              // respuesta del servidor web
//              System.out.println(sb.toString());
//              txtMensaje.setString("Encuestas activas: "+sb.toString());

//              if(sb.length()>0)
//              {
//    //              if(EncuestasActivas.establecerEncuestasActivas(sb.toString()))
//                      doAlert("Encuestas activa:\n" + sb.toString(), Alert.FOREVER);
//    //              else
//    //                  doAlert("No se pudo actualizar las encuestas", Alert.FOREVER);
//              }
//              else{
//    //              EncuestasActivas.limpiarEncuestasActivas();
//                  doAlert("No hay encuestas activas actualmente", Alert.FOREVER);
//              }
//          }
        }
      catch(UnsupportedOperationException uoe){
          doAlert(uoe.getMessage(), Alert.FOREVER);
      }
      catch(Exception e){
          doAlert(e.getMessage(), Alert.FOREVER);
      } finally {
            try {
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (httpConn != null)
                    httpConn.close();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
//         if(receptor != null)
//            return;
//        //Iniciar el hilo de recepcion
//        receptor = new Thread(this);
//        receptor.start();
    }

//     public void run(){
//
//    }

    protected void pauseApp() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    protected void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if(c==cmdSalir){
                destroyApp(true);
                notifyDestroyed();
        }
    }
    
    private void doAlert(String str, int timeout)
    {
        alerta = new Alert("Encuestas Activas", str, null, AlertType.INFO);
        alerta.setTimeout(timeout);
        Display.getDisplay(this).setCurrent(alerta, txtMensaje);
    }

    private void processRequest(String url) throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;

try
{
// Create the connection
http = (HttpConnection) Connector.open(url);

//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);

// 2) Send header information (this header is optional)
http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
// http.setRequestProperty("If-Modified-Since", "Mon, 16 Jul 2001 22:54:26 GMT");

// If you experience IO problems, try
// removing the comment from the following line
//http.setRequestProperty("Connection", "close");

// 3) Send body/data - No data for this request


//----------------
// Server Response
//----------------
System.out.println("url: " + url);
System.out.println("-------------------------");

// 1) Get status Line
System.out.println("Msg: " + http.getResponseMessage());
System.out.println("Code: " + http.getResponseCode());

// 2) Get header information
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
//System.out.println("field 0: " + http.getHeaderField(0));
//System.out.println("field 1: " + http.getHeaderField(1));
//System.out.println("field 2: " + http.getHeaderField(2));
//System.out.println("-------------------------");
//
//System.out.println("key 0: " + http.getHeaderFieldKey(0));
//System.out.println("key 1 : " + http.getHeaderFieldKey(1));
//System.out.println("key 2: " + http.getHeaderFieldKey(2));
//System.out.println("-------------------------");

System.out.println("content: " + http.getHeaderField("content-type"));
System.out.println("date: " + http.getHeaderField("date"));
System.out.println("last-modified: " + http.getHeaderField("last-modified"));

System.out.println("-------------------------");

// 3) Get data (show the file contents)
String str;
iStrm = http.openInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
iStrm.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

// Read data one character at a time
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);

str = new String(bStrm.toByteArray());
bStrm.close();
}

System.out.println("File Contents: " + str);
txtMensaje.setString(str);

//-----------------------------
// Show connection information
//-----------------------------
System.out.println("Host: " + http.getHost());
System.out.println("Port: " + http.getPort());
System.out.println("Type: " + http.getType());

// System.out.println("File: " + http.getFile());
// System.out.println("Protocol: " + http.getProtocol());
// System.out.println("URL: " + http.getURL());
// System.out.println("Query: " + http.getQuery());
}
}catch(Exception e){
e.printStackTrace();

}finally{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
}

}
